<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools>
          <!-- <div slot="right">文字</div> -->
          <template #left> 总记录数据：{{ total }}条 </template>
          <template #right>
            <el-button
              type="warning"
              size="small"
              @click="$router.push('/import')"
              >导入excel</el-button
            >
            <el-button type="danger" size="small" @click="handleDownload"
              >导出excel</el-button
            >
            <el-button type="primary" size="small" @click="hAdd"
              >新增员工</el-button
            >
          </template>
        </PageTools>

        <!-- 具体页面结构 -->
        <el-table
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
          :data="list"
          style="width: 100%"
          @sort-change="hSortChange"
        >
          <el-table-column label="序号" type="index" :index="orderIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="图像" prop="staffPhoto">
            <template slot-scope="scope">
              <!-- <img style="width: 80px" :src="scope.row.staffPhoto" alt="" /> -->
              <ImageHolder :src="scope.row.staffPhoto"></ImageHolder>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              <!-- {{ scope.row.formOfEmployment ? '正式' : '非正式' }} -->
              {{ format(scope.row.formOfEmployment) }}
              <!-- <button @click="f(scope)">1</button> -->
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            sortable="custom"
            label="入职时间"
            prop="timeOfEntry"
          />
          <!-- @click="$router.push('/employees/detail/' + scope.row.id)" -->
          <!--  @click="$router.push('/employees/detail?id=' + scope.row.id)" -->
          <!--  @click="$router.push('/employees/detail/' + scope.row.id+'/'+scope.row.username+'?uid='+scope.row.id)" -->
          <!--  $router.push({
                    name: 'employeesDetail',
                    params: { id: scope.row.id, name: scope.row.username },
                    query: {
                      uid: scope.row.id,
                    }, -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="
                  $router.push({
                    name: 'employeesDetail',
                    params: { id: scope.row.id },
                  })
                "
                >查看</el-button
              >
              <el-button
                size="mini"
                type="success"
                @click="handleEdit(scope.$index, scope.row)"
                >分配权限</el-button
              >
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="hDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!--
                :current-page 设置当前的页码
                page-sizes 可供选择的每页的条数
                page-size  当前每页的条数
                layout 决定布局元素的顺序
                total 一共有多少条数据

                @current-change: 页码变化时触发
                @size-change： 每页显示多少条 变化时触发
              -->
          <el-pagination
            :current-page="curPage"
            :page-sizes="[5, 10, 20, 30, 50]"
            :page-size="pageSize"
            layout="sizes, prev, pager, next, jumper, total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="添加员工"
      :visible.sync="isShowDialog"
      @close="hDialogClose"
    >
      <emp-dialog ref="refEmpDialog" @success="hSuccess" />
    </el-dialog>
  </div>
</template>
<script>
import EmpDialog from './empDialog.vue'
import { getEmployeeList } from '@/api/employees'
import employeeENUM from '@/constant/employees'
console.log(employeeENUM.hireType)
// const map = {
//   1: '正式',
//   2: '非正式',
//   3: '兼职'
// }
const map = employeeENUM.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

// 3
console.log(map)
import { delEmployee } from '@/api/employees'
export default {
  components: {
    EmpDialog
  },
  data() {
    return {
      pageSize: 10,
      curPage: 1,
      list: [],
      total: 0,
      isShowDialog: false,
      tHeader: []
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hDialogClose() {
      // 重置子组件的表单
      console.log(this.$refs.refEmpDialog)
      this.$refs.refEmpDialog.resetForm()
    },
    hSuccess() {
      this.isShowDialog = false

      // 用户添加成功，需要查看数据（后端添加数据时，把数据放在最后一页），跳到最后一页
      // this.curPage = 最后一页的页码
      this.total++
      this.curPage = Math.ceil(this.total / this.pageSize)

      this.loadEmployees()
    },
    hAdd() {
      this.isShowDialog = true
    },
    hDelete(id) {
      this.$confirm('确认要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    async doDel(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      // if(删除的数据是表格中的最后一条数据) {
      //   把 页码--
      // }
      if (this.list.length === 1) {
        this.curPage--
        // 处理 边界 情况
        if (this.curPage <= 0) {
          this.curPage = 1
        }
      }
      this.loadEmployees()
    },
    orderIndex(idx) {
      // console.log(idx)
      return idx + 1 + (this.curPage - 1) * this.pageSize
    },
    hSortChange(e) {
      // console.log(e)
      // 发ajax请求带上prop+order取数据回来
    },
    // 3 + 20 *1 = 23
    format(id) {
      console.log(id) // 1, 2,3 ....
      // employeeENUM.hireType 数组有3个元素  3*20 ==> 60
      return map[id] || '未知'
    },
    // format(id) {
    //   console.log(id)
    //   // employeeENUM.hireType 数组有3个元素  3*20 ==> 60
    //   const item = employeeENUM.hireType.find(item => item.id === id)
    //   if (item) {
    //     return item.value
    //   } else {
    //     return '未知'
    //   }
    // },
    f(scope) {
      console.log(scope)
    },
    async loadEmployees() {
      const res = await getEmployeeList(this.curPage, this.pageSize)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange(page) {
      // alert(page)
      this.curPage = page

      this.loadEmployees()
    },
    handleSizeChange(pagesize) {
      this.curPage = 1
      this.pageSize = pagesize
      this.loadEmployees()
    },

    /* 文件导出 */
    async handleDownload() {
      this.downloadLoading = true
      /* 补充：导出所有的数据

      思路：将获取的条数=total
      */
      const res = await getEmployeeList(this.curPage, this.total)
      const list = res.data.rows
      import('@/vendor/Export2Excel').then((excel) => {
        // const list = this.list

        // console.log(list, 22222)
        const data = this.formatJson(list)
        const tHeader = this.tHeader
        excel.export_json_to_excel({
          header: tHeader, // 设置表头
          // data: [
          //   ['张三', '男'],
          //   ['李四', '男'],
          //   ['王五', '女']
          // ],
          data, //  表体数据
          filename: '前端87', // 定义文件名
          autoWidth: false, // 定义表格宽度  默认是true
          bookType: 'txt' // 定义文件格式  默认是xlsx
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      /* 目的：得到一个二维数组并返回，并且根据需求进行导出 */
      // console.log(list, 9999)
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      this.tHeader = Object.values(map)
      // [[键所对应的值1，键所对应的值2],[1380000002，管理员]]
      return list.map((item) => {
        /*
        1-获取键======得到多少个字段
        2-根据键获取值
        */
        // Object.keys(map) // [id,password]
        return Object.keys(map).map((key) => {
          return item[key]
        }) // [968,e82,0002]
      }) // [[968,e82,0002]]
    }
  }
}
</script>
